<template>
  <div class="detail-container">
    <!-- 顶部操作栏（新增编辑/保存/取消按钮） -->
    <div class="top-bar">
      <button
          @click="goBack()"
          class="btn btn-secondary"
      >
        <i class="fas fa-arrow-left" style="margin-right: 5px;"></i>
        返回列表
      </button>
      <h2 class="page-title">
        <i class="fas fa-file-alt" style="color: #42b983; margin-right: 10px;"></i>
        {{ isEditing ? "编辑简历" : "简历详情" }}
      </h2>
      <div class="action-buttons">
        <!-- 查看模式：显示“编辑”按钮 -->
        <button
            v-if="!isEditing && resume"
            @click="enterEditMode()"
            class="btn btn-primary"
        >
          <i class="fas fa-edit" style="margin-right: 5px;"></i>
          编辑简历
        </button>
        <!-- 编辑模式：显示“保存”和“取消”按钮 -->
        <div v-if="isEditing">
          <button
              @click="submitEdit()"
              class="btn btn-success"
              :disabled="isSubmitting"
          >
            <i
                v-if="isSubmitting"
                class="fas fa-spinner fa-spin"
                style="margin-right: 5px;"
            ></i>
            {{ isSubmitting ? "保存中..." : "保存修改" }}
          </button>
          <button
              @click="cancelEdit()"
              class="btn btn-secondary"
              style="margin-left: 10px;"
          >
            <i class="fas fa-times" style="margin-right: 5px;"></i>
            取消
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑成功提示 -->
    <div v-if="successMessage" class="success-container">
      <i class="fas fa-check-circle" style="font-size: 16px; color: #42b983; margin-right: 8px;"></i>
      <span class="success-text">{{ successMessage }}</span>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading-container">
      <i class="fas fa-spinner fa-spin" style="font-size: 36px; color: #42b983;"></i>
      <div class="loading-text">加载中...</div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-container">
      <i class="fas fa-exclamation-circle" style="font-size: 36px; color: #ff4d4f;"></i>
      <div class="error-text">{{ error }}</div>
      <button
          @click="fetchResumeDetail()"
          class="btn btn-primary"
          style="margin-top: 20px;"
      >
        <i class="fas fa-sync-alt" style="margin-right: 5px;"></i>
        重试
      </button>
    </div>

    <!-- 简历详情/编辑内容 -->
    <div v-if="resume" class="resume-detail">
      <!-- 基本信息卡片（可编辑） -->
      <div class="detail-card">
        <h3 class="card-title">
          <i class="fas fa-user" style="color: #42b983; margin-right: 8px;"></i>
          基本信息
        </h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">姓名：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.name }}</span>
            <input
                v-if="isEditing"
                v-model="editForm.name"
                type="text"
                class="form-input"
                placeholder="请输入姓名"
            />
          </div>
          <div class="info-item">
            <span class="info-label">应届年份：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.graduate_year || "无" }}</span>
            <input
                v-if="isEditing"
                v-model="editForm.graduate_year"
                type="text"
                class="form-input"
                placeholder="如：24年应届生、2025届"
            />
          </div>
          <div class="info-item">
            <span class="info-label">学历：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.education }}</span>
            <select
                v-if="isEditing"
                v-model="editForm.education"
                class="form-select"
            >
              <option value="">请选择学历</option>
              <option value="大专">大专</option>
              <option value="本科">本科</option>
              <option value="硕士">硕士</option>
              <option value="博士">博士</option>
              <option value="其他">其他</option>
            </select>
          </div>
          <div class="info-item">
            <span class="info-label">求职状态：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.job_status || "无" }}</span>
            <input
                v-if="isEditing"
                v-model="editForm.job_status"
                type="text"
                class="form-input"
                placeholder="如：在校-考虑机会、离职-随时到岗"
            />
          </div>
          <div class="info-item">
            <span class="info-label">手机号：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.phone }}</span>
            <input
                v-if="isEditing"
                v-model="editForm.phone"
                type="tel"
                class="form-input"
                placeholder="请输入11位有效手机号"
            />
          </div>
          <div class="info-item">
            <span class="info-label">简历评分：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.resume_score }}分</span>
            <input
                v-if="isEditing"
                v-model="editForm.resume_score"
                type="number"
                class="form-input"
                min="0"
                max="100"
                placeholder="0-100分"
            />
          </div>
          <div class="info-item">
            <span class="info-label">待优化项：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.optimization_items }}项</span>
            <input
                v-if="isEditing"
                v-model="editForm.optimization_items"
                type="number"
                class="form-input"
                min="0"
                placeholder="如：2"
            />
          </div>
          <div class="info-item">
            <span class="info-label">个人优势：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.preponderance || "无" }}</span>
            <input
                v-if="isEditing"
                v-model="editForm.preponderance"
                type="text"
                class="form-input"
                placeholder="如：Python熟练、有项目经验"
            />
          </div>
          <div class="info-item">
            <span class="info-label">期望职位：</span>
            <span v-if="!isEditing" class="info-value">{{ resume.expectedJob }}</span>
            <input
                v-if="isEditing"
                v-model="editForm.expectedJob"
                type="text"
                class="form-input"
                placeholder="如：后端开发工程师、前端开发"
            />
          </div>
        </div>
      </div>

      <!-- 工作/实习经历（可编辑） -->
      <div v-if="(resume.work_experiences && resume.work_experiences.length > 0) || isEditing" class="detail-card">
        <div class="card-header-flex">
          <h3 class="card-title">
            <i class="fas fa-briefcase" style="color: #42b983; margin-right: 8px;"></i>
            工作/实习经历
          </h3>
          <!-- 编辑模式：添加经历按钮 -->
          <button
              v-if="isEditing"
              @click="addWorkExperience()"
              class="btn btn-primary btn-sm"
          >
            <i class="fas fa-plus" style="margin-right: 5px;"></i>
            添加经历
          </button>
        </div>
        <div class="experience-list">
          <div
              v-for="(item, index) in (editForm.work_experiences || [])"
              :key="item.id || index"
              class="experience-item"
          >
            <!-- 编辑模式：显示删除按钮 -->
            <button
                v-if="isEditing"
                @click="removeWorkExperience(index)"
                class="btn btn-danger btn-xs"
                style="float: right; margin-top: -5px;"
            >
              <i class="fas fa-trash"></i>
            </button>

            <div class="experience-header">
              <span class="experience-title">
                <span v-if="!isEditing">{{ item.company }} - {{ item.position }}</span>
                <div v-if="isEditing" class="experience-input-row">
                  <input
                      v-model="item.company"
                      type="text"
                      class="form-input-sm"
                      placeholder="公司名称"
                      style="width: 180px; margin-right: 10px;"
                  />
                  <input
                      v-model="item.position"
                      type="text"
                      class="form-input-sm"
                      placeholder="职位"
                      style="width: 150px;"
                  />
                </div>
              </span>
              <span class="experience-date">
                <span v-if="!isEditing">{{ item.start_date }} ~ {{ item.end_date || "至今" }}</span>
                <div v-if="isEditing" class="experience-input-row">
                  <input
                      v-model="item.start_date"
                      type="date"
                      class="form-input-sm"
                      style="width: 120px; margin-right: 10px;"
                  />
                  <span style="color: #666;">~</span>
                  <input
                      v-model="item.end_date"
                      type="date"
                      class="form-input-sm"
                      style="width: 120px; margin-left: 10px;"
                      placeholder="可选"
                  />
                </div>
              </span>
            </div>
            <div class="experience-content">
              <span v-if="!isEditing">{{ item.description }}</span>
              <textarea
                  v-if="isEditing"
                  v-model="item.description"
                  class="form-textarea-sm"
                  rows="2"
                  placeholder="请描述工作内容、职责和成果"
              ></textarea>
            </div>
          </div>
          <div v-if="editForm.work_experiences.length === 0 && isEditing" class="empty-tip">
            暂无工作/实习经历，点击"添加经历"按钮添加
          </div>
        </div>
      </div>

      <!-- 项目经历（可编辑） -->
      <div v-if="(resume.project_experiences && resume.project_experiences.length > 0) || isEditing" class="detail-card">
        <div class="card-header-flex">
          <h3 class="card-title">
            <i class="fas fa-project-diagram" style="color: #42b983; margin-right: 8px;"></i>
            项目经历
          </h3>
          <button
              v-if="isEditing"
              @click="addProjectExperience()"
              class="btn btn-primary btn-sm"
          >
            <i class="fas fa-plus" style="margin-right: 5px;"></i>
            添加项目
          </button>
        </div>
        <div class="experience-list">
          <div
              v-for="(item, index) in (editForm.project_experiences || [])"
              :key="item.id || index"
              class="experience-item"
          >
            <button
                v-if="isEditing"
                @click="removeProjectExperience(index)"
                class="btn btn-danger btn-xs"
                style="float: right; margin-top: -5px;"
            >
              <i class="fas fa-trash"></i>
            </button>
            <div class="experience-header">
              <span class="experience-title">
                <span v-if="!isEditing">{{ item.project_name }} - {{ item.role }}</span>
                <div v-if="isEditing" class="experience-input-row">
                  <input
                      v-model="item.project_name"
                      type="text"
                      class="form-input-sm"
                      placeholder="项目名称"
                      style="width: 180px; margin-right: 10px;"
                  />
                  <input
                      v-model="item.role"
                      type="text"
                      class="form-input-sm"
                      placeholder="项目角色"
                      style="width: 150px;"
                  />
                </div>
              </span>
              <span class="experience-date">
                <span v-if="!isEditing">{{ item.start_date }} ~ {{ item.end_date || "至今" }}</span>
                <div v-if="isEditing" class="experience-input-row">
                  <input
                      v-model="item.start_date"
                      type="date"
                      class="form-input-sm"
                      style="width: 120px; margin-right: 10px;"
                  />
                  <span style="color: #666;">~</span>
                  <input
                      v-model="item.end_date"
                      type="date"
                      class="form-input-sm"
                      style="width: 120px; margin-left: 10px;"
                  />
                </div>
              </span>
            </div>
            <div class="experience-content">
              <span v-if="!isEditing">{{ item.description }}</span>
              <textarea
                  v-if="isEditing"
                  v-model="item.description"
                  class="form-textarea-sm"
                  rows="2"
                  placeholder="请描述项目背景、职责、技术栈和成果"
              ></textarea>
            </div>
          </div>
          <div v-if="editForm.project_experiences.length === 0 && isEditing" class="empty-tip">
            暂无项目经历，点击"添加项目"按钮添加
          </div>
        </div>
      </div>

      <!-- 教育经历（可编辑） -->
      <div v-if="(resume.education_experiences && resume.education_experiences.length > 0) || isEditing" class="detail-card">
        <div class="card-header-flex">
          <h3 class="card-title">
            <i class="fas fa-graduation-cap" style="color: #42b983; margin-right: 8px;"></i>
            教育经历
          </h3>
          <button
              v-if="isEditing"
              @click="addEducationExperience()"
              class="btn btn-primary btn-sm"
          >
            <i class="fas fa-plus" style="margin-right: 5px;"></i>
            添加教育经历
          </button>
        </div>
        <div class="experience-list">
          <div
              v-for="(item, index) in (editForm.education_experiences || [])"
              :key="item.id || index"
              class="experience-item"
          >
            <button
                v-if="isEditing"
                @click="removeEducationExperience(index)"
                class="btn btn-danger btn-xs"
                style="float: right; margin-top: -5px;"
            >
              <i class="fas fa-trash"></i>
            </button>
            <div class="experience-header">
              <span class="experience-title">
                <span v-if="!isEditing">{{ item.school }} - {{ item.education }}</span>
                <div v-if="isEditing" class="experience-input-row">
                  <input
                      v-model="item.school"
                      type="text"
                      class="form-input-sm"
                      placeholder="学校名称"
                      style="width: 180px; margin-right: 10px;"
                  />
                  <select
                      v-model="item.education"
                      class="form-select-sm"
                      style="width: 100px;"
                  >
                    <option value="">学历</option>
                    <option value="大专">大专</option>
                    <option value="本科">本科</option>
                    <option value="硕士">硕士</option>
                    <option value="博士">博士</option>
                  </select>
                </div>
              </span>
              <span class="experience-date">
                <span v-if="!isEditing">{{ item.start_date }} ~ {{ item.end_date }}</span>
                <div v-if="isEditing" class="experience-input-row">
                  <input
                      v-model="item.start_date"
                      type="date"
                      class="form-input-sm"
                      style="width: 120px; margin-right: 10px;"
                  />
                  <span style="color: #666;">~</span>
                  <input
                      v-model="item.end_date"
                      type="date"
                      class="form-input-sm"
                      style="width: 120px; margin-left: 10px;"
                  />
                </div>
              </span>
            </div>
            <div class="experience-content">
              <p v-if="!isEditing" class="experience-meta">专业：{{ item.major || "无" }}</p>
              <div v-if="isEditing" class="experience-input-row" style="margin-bottom: 8px;">
                <input
                    v-model="item.major"
                    type="text"
                    class="form-input-sm"
                    placeholder="专业"
                    style="width: 150px;"
                />
              </div>
              <span v-if="!isEditing && item.description">{{ item.description }}</span>
              <textarea
                  v-if="isEditing"
                  v-model="item.description"
                  class="form-textarea-sm"
                  rows="2"
                  placeholder="获奖情况、担任职务等"
              ></textarea>
            </div>
          </div>
          <div v-if="editForm.education_experiences.length === 0 && isEditing" class="empty-tip">
            暂无教育经历，点击"添加教育经历"按钮添加
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const route = useRoute();
// 路由参数名可能是 id 或 resumeId，检查并获取
const resumeId = route.params.id || route.params.resumeId; // 简历ID（personal_info.id）

// 状态变量
const resume = ref(null); // 原始简历数据（用于展示和取消编辑）
const editForm = ref({}); // 编辑表单数据（双向绑定）
const isEditing = ref(false); // 是否处于编辑模式
const isSubmitting = ref(false); // 提交中状态
const loading = ref(true); // 加载状态
const error = ref(''); // 错误信息
const successMessage = ref(''); // 编辑成功提示

// 页面加载时获取简历详情
onMounted(() => {
  if (!resumeId) {
    error.value = '简历ID不存在';
    loading.value = false;
    return;
  }
  fetchResumeDetail();
});

// 监听resume变化，初始化编辑表单（确保编辑数据与原始数据一致）
watch(resume, (newVal) => {
  if (newVal && typeof newVal === 'object' && !Array.isArray(newVal)) {
    try {
      // 深拷贝原始数据到编辑表单（避免直接修改原始数据）
      const clonedData = JSON.parse(JSON.stringify(newVal));
      // 确保克隆的数据是对象
      if (typeof clonedData === 'object' && clonedData !== null) {
        editForm.value = clonedData;
        // 处理数字字段（避免表单显示为字符串）
        editForm.value.resume_score = Number(editForm.value.resume_score) || 0;
        editForm.value.optimization_items = Number(editForm.value.optimization_items) || 0;
        // 确保数组字段存在
        editForm.value.work_experiences = editForm.value.work_experiences || [];
        editForm.value.project_experiences = editForm.value.project_experiences || [];
        editForm.value.education_experiences = editForm.value.education_experiences || [];
      } else {
        console.error('克隆后的数据不是对象:', clonedData);
        error.value = '数据格式错误，无法加载简历';
      }
    } catch (e) {
      console.error('初始化编辑表单失败:', e);
      error.value = '数据格式错误，无法加载简历';
    }
  } else if (newVal === null) {
    // resume 被重置为 null 时，也重置 editForm
    editForm.value = {};
  }
}, { immediate: false });

// 加载简历详情
const fetchResumeDetail = async () => {
  if (!resumeId) {
    error.value = '简历ID不存在';
    loading.value = false;
    return;
  }
  
  loading.value = true;
  error.value = '';
  try {
    // 后端路由：path('resume/', include('resume.urls'))，所以完整路径是 http://127.0.0.1:8000/resume/resumes/<id>/
    const response = await axios.get(`http://127.0.0.1:8000/resume/resumes/${resumeId}/`, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    // 确保返回的数据是对象
    if (response.data && typeof response.data === 'object' && !Array.isArray(response.data)) {
      resume.value = response.data;
      console.log('获取到的简历详情:', resume.value);
    } else {
      throw new Error('返回的数据格式不正确');
    }
  } catch (err) {
    console.error('获取简历详情失败:', err);
    if (err.response) {
      if (err.response.status === 404) {
        error.value = `未找到 ID为${resumeId}的简历（personal_info.id 不存在）`;
      } else if (err.response.status === 500) {
        error.value = '服务器内部错误，请稍后重试';
      } else {
        error.value = `加载失败：${err.response.status} ${err.response.statusText}`;
      }
    } else if (err.message && (err.message.includes('Network Error') || err.message.includes('ERR_CONNECTION_REFUSED'))) {
      error.value = '无法连接到服务器，请检查后端是否启动（http://127.0.0.1:8000）！';
    } else {
      error.value = '加载简历详情失败：' + (err.message || '未知错误');
    }
  } finally {
    loading.value = false;
  }
};

// 进入编辑模式
const enterEditMode = () => {
  isEditing.value = true;
  successMessage.value = ''; // 清空之前的成功提示
};

// 取消编辑（恢复原始数据）
const cancelEdit = () => {
  isEditing.value = false;
  // 重置编辑表单为原始数据
  if (resume.value && typeof resume.value === 'object') {
    try {
      editForm.value = JSON.parse(JSON.stringify(resume.value));
      // 确保字段正确初始化
      editForm.value.resume_score = Number(editForm.value.resume_score) || 0;
      editForm.value.optimization_items = Number(editForm.value.optimization_items) || 0;
      editForm.value.work_experiences = editForm.value.work_experiences || [];
      editForm.value.project_experiences = editForm.value.project_experiences || [];
      editForm.value.education_experiences = editForm.value.education_experiences || [];
    } catch (e) {
      console.error('重置编辑表单失败:', e);
    }
  }
};

// 提交编辑（保存修改）
const submitEdit = async () => {
  // 基础校验
  if (!editForm.value.name) {
    alert('请输入姓名');
    return;
  }
  if (!editForm.value.education) {
    alert('请选择学历');
    return;
  }
  if (!editForm.value.phone || !/^1[3-9]\d{9}$/.test(editForm.value.phone)) {
    alert('请输入11位有效手机号');
    return;
  }
  if (!editForm.value.expectedJob) {
    alert('请输入期望职位');
    return;
  }

  // 验证关联经历
  const validateExperiences = () => {
    // 确保数组字段存在
    editForm.value.work_experiences = editForm.value.work_experiences || [];
    editForm.value.project_experiences = editForm.value.project_experiences || [];
    editForm.value.education_experiences = editForm.value.education_experiences || [];
    
    // 验证工作经历
    for (let i = 0; i < editForm.value.work_experiences.length; i++) {
      const item = editForm.value.work_experiences[i];
      if (!item.company.trim()) {
        alert(`工作经历${i+1}：请输入公司名称`);
        return false;
      }
      if (!item.position.trim()) {
        alert(`工作经历${i+1}：请输入职位`);
        return false;
      }
      if (!item.start_date) {
        alert(`工作经历${i+1}：请选择开始日期`);
        return false;
      }
      if (!item.description.trim()) {
        alert(`工作经历${i+1}：请输入工作描述`);
        return false;
      }
      if (item.end_date && new Date(item.end_date) < new Date(item.start_date)) {
        alert(`工作经历${i+1}：结束日期不能早于开始日期`);
        return false;
      }
    }

    // 验证项目经历
    for (let i = 0; i < editForm.value.project_experiences.length; i++) {
      const item = editForm.value.project_experiences[i];
      if (!item.project_name.trim()) {
        alert(`项目经历${i+1}：请输入项目名称`);
        return false;
      }
      if (!item.role.trim()) {
        alert(`项目经历${i+1}：请输入项目角色`);
        return false;
      }
      if (!item.start_date) {
        alert(`项目经历${i+1}：请选择开始日期`);
        return false;
      }
      if (!item.description.trim()) {
        alert(`项目经历${i+1}：请输入项目描述`);
        return false;
      }
      if (item.end_date && new Date(item.end_date) < new Date(item.start_date)) {
        alert(`项目经历${i+1}：结束日期不能早于开始日期`);
        return false;
      }
    }

    // 验证教育经历
    for (let i = 0; i < editForm.value.education_experiences.length; i++) {
      const item = editForm.value.education_experiences[i];
      if (!item.school.trim()) {
        alert(`教育经历${i+1}：请输入学校名称`);
        return false;
      }
      if (!item.education) {
        alert(`教育经历${i+1}：请选择学历`);
        return false;
      }
      if (!item.start_date) {
        alert(`教育经历${i+1}：请选择入学日期`);
        return false;
      }
      if (!item.end_date) {
        alert(`教育经历${i+1}：请选择毕业日期`);
        return false;
      }
      if (new Date(item.end_date) < new Date(item.start_date)) {
        alert(`教育经历${i+1}：毕业日期不能早于入学日期`);
        return false;
      }
    }
    return true;
  };

  if (!validateExperiences()) {
    return;
  }

  isSubmitting.value = true;
  successMessage.value = '';
  error.value = '';

  // 适配 APIView：所有路径必须包含简历ID（后端要求）
  const payload = { ...editForm.value };
  const baseURL = 'http://127.0.0.1:8000/resume';
  const candidates = [
    { method: 'patch', url: `${baseURL}/resumes/${resumeId}/` },
    { method: 'put',   url: `${baseURL}/resumes/${resumeId}/` },
    { method: 'post',  url: `${baseURL}/resumes/${resumeId}/` },
    { method: 'patch', url: `${baseURL}/resumes/update/${resumeId}/` },
    { method: 'post',  url: `${baseURL}/resumes/update/${resumeId}/` },
  ];

  let lastError = null;
  for (const opt of candidates) {
    try {
      await axios[opt.method](opt.url, payload, {
        headers: { 'Content-Type': 'application/json' }
      });

      // 保存成功后，重新加载最新数据
      await fetchResumeDetail();
      isEditing.value = false;
      isSubmitting.value = false;
      successMessage.value = '简历修改成功！';
      setTimeout(() => { successMessage.value = ''; }, 3000);
      return;
    } catch (err) {
      lastError = err;
      // 尝试下一个候选
    }
  }

  // 所有候选均失败，给出最后一次错误信息
  isSubmitting.value = false;
  if (lastError && lastError.response && lastError.response.data !== undefined) {
    const data = lastError.response.data;
    if (typeof data === 'string') {
      // 后端返回纯文本或HTML错误，尝试提取关键信息
      let errorText = data;
      // 尝试从HTML的<title>标签提取错误信息
      const titleMatch = data.match(/<title[^>]*>([^<]+)<\/title>/i);
      if (titleMatch) {
        errorText = titleMatch[1].trim();
      } else {
        // 如果没有title，尝试提取第一段有意义的内容
        const textMatch = data.match(/(?:错误|Error|失败|Failed)[^<\n]{0,100}/i);
        if (textMatch) {
          errorText = textMatch[0].trim();
        } else {
          // 截取前200字符，避免显示过长的HTML
          errorText = data.substring(0, 200).replace(/<[^>]+>/g, '').trim();
        }
      }
      alert('修改失败：' + errorText);
    } else if (typeof data === 'object') {
      const errorMsg = [];
      for (const key in data) {
        const value = data[key];
        errorMsg.push(`${key}：${Array.isArray(value) ? value.join('、') : value}`);
      }
      alert('修改失败：' + (errorMsg.length ? errorMsg.join('；') : JSON.stringify(data)));
    } else {
      alert('修改失败：' + String(data));
    }
  } else if (lastError) {
    alert('修改失败：' + lastError.message);
  } else {
    alert('修改失败：未知错误');
  }
};

// 动态添加/删除工作经历
const addWorkExperience = () => {
  if (!editForm.value.work_experiences) {
    editForm.value.work_experiences = [];
  }
  editForm.value.work_experiences.push({
    company: '',
    position: '',
    start_date: '',
    end_date: '',
    description: ''
  });
};
const removeWorkExperience = (index) => {
  editForm.value.work_experiences.splice(index, 1);
};

// 动态添加/删除项目经历
const addProjectExperience = () => {
  if (!editForm.value.project_experiences) {
    editForm.value.project_experiences = [];
  }
  editForm.value.project_experiences.push({
    project_name: '',
    role: '',
    start_date: '',
    end_date: '',
    description: ''
  });
};
const removeProjectExperience = (index) => {
  editForm.value.project_experiences.splice(index, 1);
};

// 动态添加/删除教育经历
const addEducationExperience = () => {
  if (!editForm.value.education_experiences) {
    editForm.value.education_experiences = [];
  }
  editForm.value.education_experiences.push({
    school: '',
    education: '',
    major: '',
    start_date: '',
    end_date: '',
    description: ''
  });
};
const removeEducationExperience = (index) => {
  editForm.value.education_experiences.splice(index, 1);
};

// 返回列表页
const goBack = () => {
  router.push('/resume');
};
</script>

<style scoped>
/* 原有样式保留，新增以下编辑模式相关样式 */
.action-buttons {
  display: flex;
  gap: 10px;
}

.card-header-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.form-input,
.form-select,
.form-textarea {
  padding: 10px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.1);
}

.form-input-sm {
  padding: 6px 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 13px;
}

.form-select-sm {
  padding: 6px 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 13px;
}

.form-textarea-sm {
  padding: 6px 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 13px;
  resize: vertical;
  width: 100%;
}

.experience-input-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-xs {
  padding: 2px 6px;
  font-size: 12px;
}

.btn-success {
  background-color: #52c41a;
  color: #ffffff;
}

.btn-success:hover {
  background-color: #41a616;
}

.success-container {
  background-color: #f0f9f4;
  color: #359469;
  border: 1px solid #c3e6d5;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.success-text {
  font-size: 14px;
  font-weight: 500;
}

.empty-tip {
  color: #999;
  text-align: center;
  padding: 20px;
  font-size: 14px;
  background-color: #fafafa;
  border-radius: 8px;
}

/* 原有样式保留（确保与整体风格一致） */
.detail-container {
  width: 100%;
}

.top-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  justify-content: space-between;
}

.page-title {
  color: #333;
  font-size: 22px;
  margin: 0;
  font-weight: 600;
}

.detail-card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 25px;
  margin-bottom: 25px;
}

.card-title {
  color: #333;
  font-size: 18px;
  margin-bottom: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-bottom: 8px;
}

.info-label {
  width: 80px;
  color: #666;
  font-weight: 500;
}

.info-value {
  color: #333;
  flex: 1;
}

.experience-list {
  margin-top: 15px;
}

.experience-item {
  border-left: 3px solid #42b983;
  padding-left: 15px;
  margin-bottom: 20px;
}

.experience-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.experience-title {
  color: #333;
  font-weight: 600;
  font-size: 15px;
}

.experience-date {
  color: #666;
  font-size: 13px;
}

.experience-content {
  color: #555;
  font-size: 14px;
  line-height: 1.6;
}

.loading-container, .error-container {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

.error-container {
  color: #ff4d4f;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #666;
}

.btn-secondary:hover {
  background-color: #e5e5e5;
}

.btn-primary {
  background-color: #42b983;
  color: #ffffff;
}

.btn-primary:hover {
  background-color: #359469;
}
</style>